import React, { Component } from 'react'
import { message, Row, Col, Button, Select, Table, Modal } from 'antd'
import AddRole from './../addRole'
import DeleteModel from './deleteModel.js'
import api from '../../../api/index'
import T from '../../../lib/T'
import { connect } from 'mirrorx'
// import IconDom from '../../../component/IconDom'

const Option = Select.Option
class RoleMgmt extends Component {
  constructor (props) {
    super(props)
    this.state = {
      roleList: [
        { name: 'all', value: 'all' } // 筛选下拉框里的角色列表
      ],
      dataSource: [], // 所有角色列表
      dataSourceAll: [], // 筛选功能需要保留完整角色列表
      showAddRole: false, // 新增角色.修改权限.查看权限.弹框显示/隐藏
      action: 'add', // 动作(add/view/edit)
      flag: false, // 标记 筛选功能(目前不需要 需要时删除或改为true)
      visible: false, // 删除角色确定提示框显示/隐藏
      roleId: '', // 角色ID
      roleName: '', // 角色姓名
      deleteModel: false // 删除角色时,角色有邦定子账号提示框
    }

    this.addNewRole = this.addNewRole.bind(this) // 新增角色.修改权限.查看权限共用的弹框控制
    this.renderModal = this.renderModal.bind(this) // 新增角色.修改权限.查看权限共用的弹框
    this.callBack = this.callBack.bind(this) // 新增角色及修改权限弹框确认按钮的回调
    this.onCancel = this.onCancel.bind(this) // 新增角色.修改权限.查看权限弹框取消按钮的回调
    this.getRoles = this.getRoles.bind(this) // 获取全部角色
    this.deleteRole = this.deleteRole.bind(this) // 删除角色
    this.renderDeleteModel = this.renderDeleteModel.bind(this) // 删除角色弹框
    this.deleteHandleCancel = this.deleteHandleCancel.bind(this) // 删除角色弹框取消按钮的回调
    this.deleteHandleOk = this.deleteHandleOk.bind(this) // 删除角色弹框确认按钮的回调
    this.handleChange = this.handleChange.bind(this) // 筛选角色下拉选择框选项改变
    this.rolefilter = this.rolefilter.bind(this) // 筛选角色
  }
  componentDidMount () {
    const { partnerId } = this.props.mainModel.userInfo
    this.getRoles(partnerId)
  }
  renderDeleteModel (roleId) {
    if (this.state.visible) {
      return (
        <Modal
          className='deleteRoleModel'
          closable={false}
          title='Delete'
          visible={this.state.visible}
          okText='Confirm'
          cancelText='Cancel'
          onOk={() => this.deleteHandleOk(roleId)}
          onCancel={this.deleteHandleCancel}
        >
          <p>Are you sure you want to delete this role?</p>
        </Modal>
      )
    }
  }
  deleteRole (roleId) {
    let url = api.querySubUserByRoleId.path
    let data = {
      roleId
    }
    T.ajax({
      url,
      data,
      method: 'post',
      loading: true
    }).then((res) => {
      console.log('查询所有关联的子用户', res)
      if (res.data.length > 0) { // 返回的数组列表长度大余0说明此角色有关联子账号,不能直接删除
        this.setState({ deleteModel: true })
      } else {
        this.setState({
          visible: true,
          roleId
        })
      }
    })
  }
  deleteHandleCancel () { this.setState({ visible: false }) }
  deleteHandleOk (roleId) {
    let url = api.deleteRoleById.path
    let data = {
      roleId
    }
    T.ajax({
      url,
      data,
      loading: true
    }).then((res) => {
      if (res.code === 0) {
        message.success('Role deleted successfully', 3)
        this.getRoles(this.props.mainModel.userInfo.partnerId) // 删除成功 重新获取角色列表
      }
    })
    this.setState({ visible: false })
  }
  getRoles (partnerId) {
    let arr = [] // 临时存储
    let url = api.getRolesByPartnerId.path
    let data = {
      partnerId
    }
    T.ajax({
      url,
      data,
      loading: true
    }).then((res) => {
      if (res.code === 0) {
        res.data.forEach(item => {
          arr.push({
            name: item.roleName,
            value: item.roleName
          })
        })
        this.setState({
          dataSource: res.data,
          dataSourceAll: res.data,
          roleList: [...this.state.roleList, ...arr] // 将数据追加到筛选功能角色列表里
        })
      }
    })
  }
  addNewRole (action, roleId, roleName) {
    console.log(roleId)
    this.setState({
      showAddRole: true,
      action: action,
      roleId,
      roleName
    })
  }
  handleChange (value) {
    this.setState({
      dataSource: this.state.dataSourceAll
    })
    if (value !== 'all') {
      this.rolefilter(this.state.dataSourceAll, value)
    }
  }
  rolefilter (data, value) { // 筛选选择的角色名
    let arr = data.filter(item => {
      return item.roleName === value
    })
    this.setState({
      dataSource: arr
    })
  }
  renderModal () { // 新增角色.修改权限.查看权限 共用弹框
    if (this.state.showAddRole) {
      return <AddRole
        action={this.state.action}
        roleId={this.state.roleId}
        dataSource={this.state.dataSource}
        roleName={this.state.roleName}
        visible={this.state.showAddRole}
        callBack={this.callBack}
        onCancel={this.onCancel}
      />
    }
  }
  callBack (roleName = '', resourceList = []) { // OK按钮回调
    let url = api.addRole.path
    let data = {
      roleName,
      resourceList
    }
    T.ajax({
      url,
      data,
      method: 'post',
      loading: true
    }).then((res) => {
      if (res.code === 0) {
        message.success('Role created successfully', 3)
        this.getRoles(this.props.mainModel.userInfo.partnerId)
      }
    })
    this.setState({
      showAddRole: false
    })
  }
  onCancel () { // 取消按钮回调
    this.setState({
      showAddRole: false
    })
  }
  render () {
    const { dataSource } = this.state
    let { grantedMenus } = this.props.menuModel

    let menuAuth = false
    if (grantedMenus) {
      console.log('grantedMenus', grantedMenus)
      menuAuth = T.getMenuAuth('Account Management', grantedMenus)
    }

    let columns = [{
      title: 'Role Name',
      dataIndex: 'roleName',
      key: 'roleName'
    }, {
      title: 'Operations',
      key: 'operation',
      dataIndex: 'Operations',
      render: (text, record) => {
        // console.log('record', record)
        if (record.roleId) {
          return (
            record.isDefault // 判断是否为默认角色
              ? (<a href='javascript:;' onClick={() => { this.addNewRole('view', record.roleId, record.roleName) }}>View</a>)
              : (
                <p>
                  <a
                    disabled={!menuAuth}
                    href='#'
                    onClick={() => this.deleteRole(record.roleId)}>Delete</a>
                  <span className='ml10 font-gap'>|</span>
                  <a
                    disabled={!menuAuth}
                    href='javascript:;'
                    className='ml10'
                    onClick={() => { this.addNewRole('edit', record.roleId, record.roleName) }}>Edit</a>
                </p>
              )
          )
        } else {
          return null
        }
      }
    }]
    return (
      <Row>
        <Col span='24'>
          <Row className='rolemgmt'>
            <Col span='12'>
              <Button
                disabled={!menuAuth}
                type='primary' onClick={() => { this.addNewRole('add') }}>＋ New Role</Button>
            </Col>
            <Col span='12' className='mb18'>
              {
                this.state.flag // 筛选功能(暂时不需要)
                  ? <Select defaultValue={this.state.roleList[0].value} style={{ width: 200 }} onChange={this.handleChange}>
                    {
                      this.state.roleList.map((item, index) => {
                        return <Option value={item.value} key={index}>{item.name}</Option>
                      })
                    }
                  </Select> : null
              }
            </Col>

          </Row>
          <Row>
            <Col>
              <Table
                className='roleMgmtContent'
                bordered
                dataSource={dataSource}
                columns={columns}
                pagination={{ showQuickJumper: true }}
              />
            </Col>
          </Row>
        </Col>
        <DeleteModel
          handleOk={() => this.setState({ deleteModel: false })}
          visible={this.state.deleteModel} />
        {this.renderModal()}
        {this.renderDeleteModel(this.state.roleId)}
      </Row>
    )
  }
}
export default connect(state => {
  return state
})(RoleMgmt)
